1 将NodeJS的依赖进行打包
写了一个NodeJS工程,主文件有一堆依赖,需要对外引用,而对应的依赖文件在特定环境下又用不起来。
于是将主文件及其依赖打包到一个文件,使用如下命令:
browserify src-main.js --standalone exportModuleName>dst-main.js --node
上面的命令会将src-main.js打包起来,并能同时浏览器和NodeJS环境下运行。但下面的情况除外:
1.1 一个坑
查看 node-browserify 文档,参数说明如下
1 | --bare |
即使使用了–node 参数,browserify还是会处理__dirname 导致转换后的代码,跟转换前的代码运行结果不一致。可以用下面的代码测一下:
module.js
1 | var sysFs = require('fs'); |
然后通过 browserify module.js --standalone exportModuleName>module-bundle.js --node
然后查看module-bundle.js的代码,__dirname被转换写死了。
原则上这个是需要browserify中处理这个参数逻辑,也没找到其他能规避的参数,既然都强制使用–node了为什么还需要Node环境的变量呢?
这里提了好些个Issue。
2 NodeJS的模块,在浏览器里面跑
直接看这里
将NodeJS的单元测试模块直接,转换为浏览器可用的版本,在浏览器里面运行同样的代码。
使用browserify src.js > dst.js
即可。
3 参考资料
- 浏览器加载 CommonJS 模块的原理与实现
- 解析browserify工作原理
- Browserify原理
- browserify运行原理分析
- 通过 Browserify 在浏览器中使用 NodeJS 模块
- browserify.org
- node-browserify
最后更新: 2022年03月02日 03:32
原始链接: http://rawbin-.github.io/dev-tools/2016-02-18-using-browserify/